<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams">
        <el-row>
          <el-col :span="3">
            <el-form-item prop="keywords" label="关键字:">
              <el-input
                v-model="queryParams.keywords"
                placeholder="关键字"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="3">
            <el-form-item prop="settlement" label="结算方式:">
              <Dict v-model="queryParams.settlement" code="SETTLEMENT" />
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="3">
            <el-form-item prop="educational" label="学历要求:">
              <Dict v-model="queryParams.educational" code="educational" />
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="3">
            <el-form-item prop="createTimes" label="创建时间:">
              <el-date-picker
                v-model="queryParams.createTimes"
                type="daterange"
                unlink-panels
                value-format="YYYY-MM-DD"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :shortcuts="shortcuts"
                :size="size"
              />
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="3">
            <el-form-item prop="publishTimes" label="发布时间:">
              <el-date-picker
                v-model="queryParams.publishTimes"
                type="daterange"
                unlink-panels
                value-format="YYYY-MM-DD"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :shortcuts="shortcuts"
                :size="size"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row justify="end">
          <el-col :span="2">
            <el-form-item>
              <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
              <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button type="success" icon="plus" @click="handleOpenDialog()">新增</el-button>
      </div>

      <el-table ref="dataTableRef" v-loading="loading" :data="jobList" highlight-current-row border>
        <el-table-column label="岗位名称" prop="name" min-width="100" />
        <el-table-column label="岗位标题" prop="title" min-width="100" />
        <el-table-column label="薪资范围" prop="hourlyWage" min-width="100" />
        <el-table-column label="结算方式" prop="settlement" min-width="50">
          <template #default="scope">
            <DictLabel v-model="scope.row.settlement" code="SETTLEMENT" />
          </template>
        </el-table-column>
        <el-table-column label="学历要求" prop="educational" min-width="50">
          <template #default="scope">
            <DictLabel v-model="scope.row.educational" code="EDUCATIONAL" />
          </template>
        </el-table-column>
        <el-table-column label="工作时间" prop="workTime" min-width="80" />
        <el-table-column label="工作时段" prop="workHours" min-width="80" />
        <el-table-column label="工作地点" prop="workLocation" min-width="150" />
        <el-table-column label="创建时间" prop="createTime" width="200" />
        <el-table-column label="发布时间" prop="publishTime" width="200" />
        <el-table-column label="创建人" prop="createUserName" width="150" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <DictLabel v-model="scope.row.status" code="JOB_STATUS" />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="220">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 1"
              type="primary"
              size="small"
              link
              icon="edit"
              @click="handleOpenDialog(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              v-if="scope.row.status === 1"
              type="success"
              size="small"
              link
              icon="sell"
              @click="handlePublishDialog(scope.row.id)"
            >
              发布
            </el-button>
            <el-button
              v-if="scope.row.status === 2 || scope.row.status === 3"
              type="primary"
              size="small"
              link
              icon="view"
              @click="handleViewDialog(scope.row.id)"
            >
              查看
            </el-button>
            <el-button
              v-if="scope.row.status === 2"
              type="danger"
              size="small"
              link
              icon="soldOut"
              @click="handleSoldOutDialog(scope.row.id)"
            >
              下架
            </el-button>
            <el-button
              v-if="scope.row.status === 1"
              type="danger"
              size="small"
              link
              icon="delete"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 岗位信息 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="900px"
      @close="handleCloseDialog"
    >
      <el-form
        ref="jobFormRef"
        v-loading="dialogLoad"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="岗位标题" prop="title">
              <el-input
                v-model="formData.title"
                :disabled="formData.status !== 1"
                placeholder="请输入岗位标题"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="岗位名称" prop="name">
              <el-input
                v-model="formData.name"
                :disabled="formData.status !== 1"
                placeholder="请输入岗位名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="行业类型" prop="type">
              <Dict v-model="formData.type" :disabled="formData.status !== 1" code="JOB_TYPE" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="薪资范围" prop="hourlyWage">
              <el-input
                v-model="formData.hourlyWage"
                :disabled="formData.status !== 1"
                placeholder="请输入薪资范围"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="结算方式" prop="settlement">
              <Dict
                v-model="formData.settlement"
                :disabled="formData.status !== 1"
                type="radio"
                code="SETTLEMENT"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="岗位描述" prop="description">
              <div class="editor-container">
                <quill-editor
                  ref="descEditor"
                  v-model:content="formData.description"
                  contentType="html"
                  theme="snow"
                  :options="editorOptions"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="学历要求" prop="educational">
              <Dict
                v-model="formData.educational"
                :disabled="formData.status !== 1"
                type="radio"
                style="width: 500px"
                code="EDUCATIONAL"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工作时间" prop="workTime">
              <el-input
                v-model="formData.workTime"
                :disabled="formData.status !== 1"
                placeholder="请输入工作时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工作时段" prop="workHours">
              <el-input
                v-model="formData.workHours"
                :disabled="formData.status !== 1"
                placeholder="请输入工作时段"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="工作要求" prop="jobRequirements">
              <div class="editor-container">
                <quill-editor
                  ref="jobReqEditor"
                  v-model:content="formData.jobRequirements"
                  contentType="html"
                  theme="snow"
                  :options="editorOptions"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="工作地点" prop="workLocation">
              <el-input
                v-model="formData.workLocation"
                :disabled="formData.status !== 1"
                placeholder="请输入工作地点"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="福利待遇" prop="welfare">
              <el-input
                v-model="formData.welfare"
                type="textarea"
                :disabled="formData.status !== 1"
                placeholder="请输入福利待遇"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="formData.status === 1" type="primary" @click="handleSubmit">
            保存
          </el-button>
          <el-button v-if="formData.status === 1" type="success" @click="handlePublishForm">
            保存并发布
          </el-button>
          <el-button @click="handleCloseDialog">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="viewDialog.visible"
      :title="viewDialog.title"
      width="900px"
      @close="handleCloseView"
    >
      <el-form v-loading="dialogLoad">
        <el-row>
          <el-col :span="24">
            <el-form-item label="岗位标题:" prop="title">
              {{ formData.title }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="岗位名称:" prop="name">
              {{ formData.name }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="行业类型:" prop="type">
              <DictLabel v-model="formData.type" code="JOB_TYPE" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="薪资范围:" prop="hourlyWage">
              {{ formData.hourlyWage }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="结算方式:" prop="settlement">
              <DictLabel v-model="formData.settlement" code="SETTLEMENT" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="学历要求:" prop="educational">
              <DictLabel v-model="formData.educational" code="EDUCATIONAL" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="岗位描述:" prop="description">
              <div class="editor-container">
                <div class="ql-container ql-snow ql-disabled">
                  <div class="ql-editor ql-blank" v-html="formData.description"></div>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="工作时间:" prop="workTime">
              {{ formData.workTime }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工作时段:" prop="workHours">
              {{ formData.workHours }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="工作要求:" prop="jobRequirements">
              <div class="editor-container">
                <div class="ql-container ql-snow ql-disabled">
                  <div class="ql-editor ql-blank" v-html="formData.jobRequirements"></div>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="工作地点:" prop="workLocation">
              {{ formData.workLocation }}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="福利待遇:" prop="welfare">
              {{ formData.welfare }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-if="formData.publishTime" :span="6">
            <el-form-item label="发布时间:" prop="welfare">
              {{ formData.publishTime }}
            </el-form-item>
          </el-col>
          <el-col v-if="formData.soldOutTime" :span="6">
            <el-form-item label="下架时间:" prop="welfare">
              {{ formData.soldOutTime }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="commandType === 1" type="success" @click="handlePublish(formData.id)">
            确认发布
          </el-button>
          <el-button v-if="commandType === 2" type="danger" @click="handleSoldOut(formData.id)">
            确认下架
          </el-button>
          <el-button @click="handleCloseView">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import JobApi, { JobForm, JobPageQuery, JobPageVO } from "@/api/job/job.api";
import dayjs from "dayjs";
import { QuillEditor } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
// 编辑器配置
const editorOptions = ref({
  modules: {
    toolbar: [
      ["bold", "italic", "underline", "strike"], // 粗体、斜体
      [{ list: "ordered" }, { list: "bullet" }], // 列表
      [{ header: [1, 2, 3, false] }], // 标题
      ["link", "image"], // 链接、图片
      [{ color: [] }, { background: [] }], // 颜色
      ["clean"], // 清除格式
    ],
  },
  placeholder: "请输入内容...",
});

const commandType = ref<number>();

const size = ref<"default" | "large" | "small">("default");

/**
 * 日期选择范围
 */
const shortcuts = [
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "最近一个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "最近三个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

defineOptions({
  name: "Job",
  inheritAttrs: false,
});

const queryFormRef = ref();
const jobFormRef = ref();

const descEditor = ref();
const jobReqEditor = ref();

const loading = ref(false);
const total = ref(0);

const queryParams = reactive<JobPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 兼职表格数据
const jobList = ref<JobPageVO[]>();

// 查询
function handleQuery() {
  loading.value = true;
  if (queryParams.publishTimes) {
    queryParams.publishTimeStart = queryParams.publishTimes[0];
    queryParams.publishTimeEnd = queryParams.publishTimes[1];
  } else {
    queryParams.publishTimeStart = undefined;
    queryParams.publishTimeEnd = undefined;
  }
  if (queryParams.createTimes) {
    queryParams.createTimeStart = queryParams.createTimes[0];
    queryParams.createTimeEnd = queryParams.createTimes[1];
  } else {
    queryParams.createTimeStart = undefined;
    queryParams.createTimeEnd = undefined;
  }
  JobApi.getPage(queryParams)
    .then((data) => {
      jobList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  queryParams.settlement = "";
  queryParams.educational = "";
  queryParams.createTimes = lastWeek();
  handleQuery();
}

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 发布弹窗
const viewDialog = reactive({
  title: "",
  visible: false,
});

const dialogLoad = ref(false);

// 表单
const formData = reactive<JobForm>({});

// 打开弹窗
function handleOpenDialog(id?: string) {
  formData.status = 1;
  dialog.visible = true;
  if (descEditor.value) {
    descEditor.value.getQuill().setText("\n");
    jobReqEditor.value.getQuill().setText("\n");
    descEditor.value.getQuill().enable();
    jobReqEditor.value.getQuill().enable();
  }
  if (id) {
    dialog.title = "修改岗位信息";
    dialogLoad.value = true;
    JobApi.getFormData(id).then((data) => {
      dialog.title = data.status === 1 ? "修改岗位信息" : "岗位信息";
      dialogLoad.value = false;
      Object.assign(formData, data);
      descEditor.value.getQuill().enable(data.status === 1);
      jobReqEditor.value.getQuill().enable(data.status === 1);
    });
  } else {
    dialog.title = "新增岗位";
  }
}

const rules = reactive({
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  name: [{ required: true, message: "请输入岗位名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择行业类型", trigger: "blur" }],
  hourlyWage: [{ required: true, message: "请输入薪资范围", trigger: "blur" }],
  settlement: [{ required: true, message: "请选择结算方式", trigger: "blur" }],
  educational: [{ required: true, message: "请选择学历要求", trigger: "blur" }],
  workTime: [{ required: true, message: "请输入工作时间", trigger: "blur" }],
  workHours: [{ required: true, message: "请输入工作时段", trigger: "blur" }],
  workLocation: [{ required: true, message: "请输入工作地点", trigger: "blur" }],
});

// 提交岗位表单
function handleSubmit() {
  jobFormRef.value.validate((valid: any) => {
    if (valid) {
      dialogLoad.value = true;
      const id = formData.id;
      if (id) {
        const {
          revision,
          createTime,
          createUserId,
          createUserName,
          updateTime,
          updateUserId,
          updateUserName,
          ...submitData
        } = formData;
        JobApi.update(id, submitData)
          .then(() => {
            ElMessage.success("修改成功");
          })
          .finally(() => (dialogLoad.value = false));
      } else {
        JobApi.create(formData)
          .then(() => {
            ElMessage.success("新增成功");
          })
          .finally(() => (dialogLoad.value = false));
      }
    }
  });
}

// 保存并发布岗位信息
function handlePublishForm() {
  jobFormRef.value.validate((valid: any) => {
    if (valid) {
      dialogLoad.value = true;
      const {
        revision,
        createTime,
        createUserId,
        createUserName,
        updateTime,
        updateUserId,
        updateUserName,
        ...submitData
      } = formData;
      JobApi.publishForm(submitData)
        .then(() => {
          ElMessage.success("发布成功");
          handleCloseDialog();
          handleResetQuery();
        })
        .finally(() => (dialogLoad.value = false));
    }
  });
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;

  resetFormData();
}

function resetFormData() {
  if (jobFormRef.value) {
    jobFormRef.value.resetFields();
    jobFormRef.value.clearValidate();
  }

  formData.id = undefined;
  formData.description = undefined;
  formData.jobRequirements = undefined;
  formData.publishTime = undefined;
  formData.soldOutTime = undefined;
  formData.revision = undefined;
  formData.createTime = undefined;
  formData.createUserId = undefined;
  formData.createUserName = undefined;
  formData.updateTime = undefined;
  formData.updateUserId = undefined;
  formData.updateUserName = undefined;
}

// 发布岗位
function handlePublish(id?: string) {
  if (id) {
    JobApi.publishById(id).then(() => {
      ElMessage.success("发布成功");
      handleResetQuery();
      viewDialog.visible = false;
    });
  }
}

// 发布岗位弹窗
function handlePublishDialog(id: string) {
  commandType.value = 1;
  handleViewDialog(id);
}

//下架岗位弹窗
function handleSoldOutDialog(id: string) {
  commandType.value = 2;
  handleViewDialog(id);
}

function handleViewDialog(id: string) {
  viewDialog.visible = true;
  if (descEditor.value) {
    descEditor.value.getQuill().setText("\n");
    jobReqEditor.value.getQuill().setText("\n");
  }
  viewDialog.title = "岗位信息";
  dialogLoad.value = true;
  JobApi.getFormData(id).then((data) => {
    dialogLoad.value = false;
    Object.assign(formData, data);
    descEditor.value.getQuill().enable(false);
    jobReqEditor.value.getQuill().enable(false);
  });
}

function handleCloseView() {
  viewDialog.visible = false;
  commandType.value = 0;
  resetFormData();
}

// 下架岗位
function handleSoldOut(id?: string) {
  if (id) {
    JobApi.soldOutById(id).then(() => {
      ElMessage.success("下架成功");
      handleResetQuery();
    });
  }
}
// 删除岗位
function handleDelete(id: string) {
  ElMessageBox.confirm("当前操作将永久删除该岗位信息，是否继续?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      JobApi.deleteById(id)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      // ElMessage.info("已取消删除");
    }
  );
}

function lastWeek() {
  const end = new Date();
  const start = new Date();
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
  return [dayjs(start).format("YYYY-MM-DD"), dayjs(end).format("YYYY-MM-DD")];
}

onMounted(() => {
  queryParams.createTimes = lastWeek();
  handleQuery();
});
</script>

<style lang="scss" scoped>
.editor-container {
  height: 500px;
  width: 700px;
  margin-bottom: 50px;
}
.viewer {
  .ql-toolbar.ql-snow {
    display: none !important;
  }
}
</style>
